<script setup>
import PageContainer from '@/components/pageContainer.vue'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { updatePassword } from '@/api/user'
import { useUserStore } from '@/store'
import { useRouter } from 'vue-router'
const router = useRouter()
const form = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})
const rules = {
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度必须是6-15位的非空字符串',
      trigger: 'blur'
    }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度必须是6-15位的非空字符串',
      trigger: 'blur'
    },
    { validator: validateNewPwd, trigger: 'blur' }
  ],
  re_pwd: [
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度必须是6-15位的非空字符串',
      trigger: 'blur'
    },
    { required: true, message: '请再次确认新密码', trigger: 'blur' },

    { validator: validateConfirmNewPwd, trigger: 'blur' }
  ]
}

function validateNewPwd(rule, value, callback) {
  if (value === form.value.old_pwd) {
    callback(new Error('新密码不能与原密码相同'))
  }
}

function validateConfirmNewPwd(rule, value, callback) {
  if (value !== form.value.new_pwd) {
    callback(new Error('两次输入的密码不一致'))
  }
}
const FormRef = ref()
async function submitPwd() {
  await FormRef.value.validate
  // 在这里处理提交修改密码的逻辑
  await updatePassword(form.value)
  ElMessage.success('修改成功')
  useUserStore().removeToken
  useUserStore().setUser({})
  router.push('/login')
}

function resetForm() {
  form.value = {
    old_pwd: '',
    new_pwd: '',
    re_pwd: ''
  }
}
</script>
<template>
  <PageContainer title="重置密码">
    <el-col :span="12">
      <el-form :model="form" :rules="rules" ref="FormRef" label-width="100px">
        <el-form-item label="原密码" prop="old_pwd">
          <el-input
            required="true"
            v-model="form.old_pwd"
            show-password="false"
            placeholder="请输入原密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="new_pwd">
          <el-input
            required="true"
            v-model="form.new_pwd"
            show-password="false"
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="re_pwd">
          <el-input
            required="true"
            v-model="form.re_pwd"
            show-password="false"
            placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitPwd">修改密码</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </PageContainer>
</template>
